var productView;

$(function() {	
	Backbone.sync = function (method, model, options) {	 		
	};	
	 _.templateSettings = {
		       interpolate : /\{\{(.+?)\}\}/g
   };
	 
var Product = Backbone.Model.extend({
	defaults:{		
		index : 0,
		productPrice: 0,
		productCount: 0,
		eachSaleAmt: 0,
		eachSaleRemark: "",
		productName: "",
		productForm: "",
		productCode: "",
		unit: "",
		eachSaleAmt: 0,
		eachSaleRemark: "",
		ytCode:"",
		readonly : false			
	},		
	initialize: function(item){		
		this.bind("change:productCount", this.changeCount, this);
		this.bind("change:eachSaleAmt", this.changeAmt, this);		
	},		
	changeCount: function(){
		productView.calCountAmt();
	},
	changeAmt : function(){
		productView.calCountAmt();
	},	
	save : function(){		
	},
	clear : function() {
		this.destroy();
	},			 
    toggle: function() {
      this.set("sel", !this.get("sel"));
    }   
});	


var ProductList = Backbone.Collection.extend({		
	model: Product,
	
	initialize : function(){	
		this.bind('add', this.onAdd, this); 
		this.bind('remove', this.onRemove, this);
	
	},	
	sels: function() {
	      return this.where({sel: true});
	},
	onAdd: function(){
		this.reOrder();
	},
	onRemove: function(){
		this.reOrder();
		productView.calCountAmt();	
	},
	reOrder : function(){		
		for(var i = 0; i < this.length; i++){
			var product = this.at(i);		
			product.set("index", i+1);			
		}
	}	
});

products = new ProductList;

var ItemView = Backbone.View.extend({		
	tagName: "tr",		
	template : $('#product_template').html(),			
	initialize : function(){	
	   this.model.bind('destroy', this.remove, this); 
	   this.model.bind('change', this.render, this);
	   this.model.bind("focus", this.focus, this);
	},
	events:{					
		"mouseover"  : "onMouseover",
		"mouseout"   : "onMouseout",	
		"click .plusLite" : "addRow",
		"click .delLite"  : "deleteRow",
		//"change input[name = 'showProductName']" : "changeProductName",
		"change input[name = 'showProductCode']" : "changeProductCode",
		"change input[name = 'SalePrice']" : "changeSalePrice",
		"change input[name = 'SaleCount']" : "changeSaleCount",
		"change input[name = 'UnitName']" :   "changeUnitName",
		"change input[name = 'EachSaleAmt']" : "changeEachSaleAmt",
		"change input[name = 'EachSaleRemark']" : "changeEachSaleRemark",
		"click .choseGoods" : "selectProduct"
	},	
	onMouseover: function(){		
	 this.$('.choseGoods').show();	
	},
	
	onMouseout: function(){
	  this.$('.choseGoods').hide();
	},
	addRow: function(){		
	    productView.addOneAfter(this.model.get("index"));
	},
	
	deleteRow: function() {	   
		if (products.length > 1){
			this.model.destroy();
		}			  
	},
	changeProductName: function(event){		
	  var val =  this.$("input[name = 'showProductName']" ).val();
	  this.model.set("productName", val);	 
	},
	changeProductCode: function(event){
	  var val = this.$("input[name = 'showProductCode']" ).val();
	  this.model.set("productCode", val);	
	},
	
	changeSalePrice: function(event){
	  var val = this.$("input[name = 'SalePrice']" ).val();
	  this.model.set("productPrice", val);
	  calSaleAmt(this.model);
	},
	changeSaleCount: function(event){
	  var val = this.$("input[name = 'SaleCount']" ).val();
	  this.model.set("productCount", val);
	  calSaleAmt(this.model);
	},
	changeUnitName: function(event){
	  var val = this.$("input[name = 'UnitName']" ).val();
	  this.model.set("unit", val);
	},
	changeEachSaleAmt: function(event){
	  var val = this.$("input[name = 'EachSaleAmt']" ).val();
	  this.model.set("eachSaleAmt", val);
	  calSalePrice(this.model);
	},
	changeEachSaleRemark: function(event){
	  var val = this.$("input[name = 'EachSaleRemark']" ).val();
	  this.model.set("eachSaleRemark", val);
	},
	
	//选择商品
	selectProduct: function(){
		SelectProductByBusi(this.model.get("index"), "Sale");
	},
    focus: function(selector){
    	$(this.el).find(selector).focus();
    },
    //智能提示
	autoComplete:function(obj){			
		var view = this;
		var index = obj.get("index");																						  
        var productheader = { mnCode: "助记符", productName: "商品名称", productForm: "规格", productStock: "库存"};
	    $(this.el).find("input:text[name='showProductName']").each(function () {	    	
	        $(this).autoComplete({
	            header: productheader,
	            url: "/ProductInfo/getProduct",
	            width: 400,
	            selected: function (o) {	  	            	
	                var jsonn = [];
	                o["productCount"] = 1;
	                jsonn.push(o);	               
	                SelectProductOK(jsonn, index);     
	              
	                //如果最后一行，则新增一行
	                if (index == products.length){	               
	                	view.addRow();
	                }	  
	                //设置下一行焦点
	                productView.setFocus(index+1, "input[name='showProductName']");	                                          
	            }
	      });
	    });		    
	},	
	render:function(){		
		var	template = _.template(this.template, this.model.toJSON());				
		$(this.el).html(template);
		this.autoComplete(this.model);
		$(this.el).addClass("productItem");
		if (this.model.get("readonly")){
			$(this.el).find("input:text[autoComplete='off']").css({ "border": "#000000 0px solid" });		     
			$(this.el).find('input[name="showProductCode"]').attr("readonly", "readonly");
			$(this.el).find('input[name="showProductCode"]').attr("unselectable", "on");    	
		}
		return this;
	}
});

var ProductView = Backbone.View.extend({
	amtCount: 0,
	totalCount: 0,    
	otherFee: 0,	
	faReceAmt: 0,
	el : $('body'),
	initialize : function(){		
		for(var i = 0; i< 6; i++ ){						   
		     products.add(new Product());					    
		}	
		
		var copySaleId = this.$("#CopySaleId").val();
		if (copySaleId != 0){
			this.copyFromSale(copySaleId);
		}
 	   this.render();
	},		
	events:{
		"change  #OtherFee" : "calDiscountAmt",
		"change  #SaleAmt" : "calDiscountAmt",		
		"click .SaveDataToList" : "SaveDataToList",
		"click .SaveData"       : "SaveData",
	},		
	render : function(){	
		this.$("#tabProducts .productItem").remove();
		for(var i = 0; i < products.length; i++){
			var product = products.at(i);		
			this.addOne(product);
		}
	},
	
	//添加一个任务到页面id为todo-list的div/ul中
	addOne: function(product){			
		var view = new ItemView({model : product});			
		this.$("#tabProducts #total").before(view.render().el);		
	},		
	clearOne: function(product){
		product.destroy();
	},
	addOneAfter: function(index){		
		var product = new Product();
		products.add(product, {at: index});		
		this.render();
	},
	
	clearAll : function(){
		products.each(this.clearOne);
	},
	
	allAll:function(){
		products.each(this.addOne);
	},
	
	selectProductOK: function(addProducts, index){					
		var start = index-1;		
		var j = addProducts.length - (products.length - start);		
		for(var i = 0; i < j; i++ ){
			products.add(new Product());			
		}
		if (j > 0) this.render();
		
		for(var i = 0; i < addProducts.length; i++){
			var addProduct = addProducts[i];
			addProduct.index = start+1;		
			addProduct.readonly = true;
			if(start < products.length){				
				var product = products.at(start);					
				product.set(addProduct);						
			}		
			start++;			
		};			
	},
	//计算总金额
	calCountAmt : function() {	   		
		console.log("calCountAmt")
	    this.amtCount = 0;
	    this.totalCount = 0;	  
	    
	    for(var i = 0; i < products.length; i++){
			var product = products.at(i);		
			this.totalCount += Number(product.get("productCount"));
			this.amtCount += product.get("eachSaleAmt");
		}	   

	   this.$("#SaleAmt").val(this.amtCount.toFixed(2));
	   this.$("#spanTotalCount").val(this.totalCount.toFixed(2));	 
	    //计算折后金额
	   this.calDiscountAmt();
	},
	//计算折后金额 默认填充实收金额
	calDiscountAmt: function() {
	   this.otherFee = Number(this.$("#OtherFee").val());	   
	   this.amtCount = Number(this.$("#SaleAmt").val());			
	   this.faReceAmt = Number(this.otherFee) + Number(this.amtCount);	   
	   $("#ReceAmt").val(this.faReceAmt.toFixed(2));
	   console.log("calDiscountAmt");
	},
	setFocus: function(index, selecter){
		 for(var i = 0; i < products.length; i++){
				var product = products.at(i);		
			    if (product.get("index") == index){
			    	product.trigger("focus", selecter);			    
			    }
		}	  		
	},
	SaveDataToList: function(){
		this.SaveData(1);
	},
	SaveData:  function (IsToList) {
	    $(".button").hide();   
	    if (ValidateForm()) {     
	    	$("#IsToList").val(IsToList);
	    	
	    	var productData = [];
	    	for(var i = 0; i < products.length; i++){
				var product = products.at(i);		
				productData.push(product);
	    	}	  		
	    	
	    	$("#productData").val(JSON.stringify(productData));
	    	
            var isPrint = $("#chkPrint").attr("checked");
            if (isPrint) {
                $("#IsPrint").val(1);
                $("form").submit();
            } else {
                $("#IsPrint").val(0);
                $("form").submit();
            };
	     }
	    else {
	        $(".button").show();
	    }
	    parent.UpdateTabFirst();
	},
	copyFromSale: function(copySaleId){
		
		 $.post("/Sale/Get", {SaleId:copySaleId}, function (sale, resultState) {
		        if (resultState == "success") {    			        
		        	$("#OrderNo").val(sale.orderNo);
		        	$("#Buyer").val(sale.buyer);
		        	var jsonn = [];
		            for(var i = 0 ; i < sale.saleItems.length; i++){
		             	var saleItem = sale.saleItems[i];	
		             	jsonn.push(saleItem);	
		             }
		            SelectProductOK(jsonn, 1); 
		        }		            
		       
		    },"json");
	}	
});		

  productView = new ProductView;
});

function delSel() {		
	productView.delSels();
}
